package com._119yn.host.gst200.service.impl;

import com._119yn.host.gst200.constant.SysAttrs;
import com._119yn.host.gst200.database.dao.SysAttrDao;
import com._119yn.host.gst200.database.entity.SysAttr;
import com._119yn.host.gst200.service.SysAttrService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysAttrServiceImpl implements SysAttrService, ApplicationRunner {

    private final SysAttrDao sysAttrDao;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        put(SysAttrs.HOST_TIMEOUT, "60");
    }

    @Override
    public String get(String code) {
        SysAttr sysAttr = sysAttrDao.selectByCode(code);
        if (sysAttr == null) {
            return null;
        } else {
            return sysAttr.getData();
        }
    }

    @Override
    public void put(String code, String data) {
        SysAttr sysAttr = sysAttrDao.selectByCode(code);
        if (sysAttr == null) {
            sysAttr = new SysAttr();
            sysAttr.setCode(code);
            sysAttr.setData(data);
            sysAttrDao.insert(sysAttr);
        } else {
            sysAttr.setData(data);
            sysAttrDao.updateByCode(sysAttr);
        }
    }

    @Override
    public void remove(String code) {
        sysAttrDao.deleteByCode(code);
    }

    @Override
    public boolean getBoolean(String code) {
        String data = get(code);
        if (data == null) {
            return false;
        } else {
            return Boolean.parseBoolean(data);
        }
    }

    @Override
    public void putBoolean(String code, boolean data) {
        put(code, data ? "true" : "false");
    }

    @Override
    public Integer getInteger(String code) {
        String data = get(code);
        if (data == null) {
            return null;
        } else {
            return Integer.parseInt(data);
        }
    }

    @Override
    public void putInteger(String code, Integer data) {
        put(code, data != null ? "%d".formatted(data) : null);
    }

}
